<?php
/**
 * 联盟管理
 */
namespace app\service;

use app\common\model\RoomModel;
use app\service\User;
use app\common\model\ConfigModel;

Class Union
{
    /**
     * 联盟数据表
     *
     * @var [type]
     */
    public $r_model;

    /**
     * 用户信息服务
     *
     * @var [type]
     */
    public $u_service;

    /**
     * 配置数据表
     *
     * @var [type]
     */
    public $c_model;

    public function __construct()
    {
        $this->r_model = new RoomModel;
        $this->u_service = new User;
        $this->c_model = new ConfigModel;
    }

    /**
     * 获取全部联盟
     *
     * @return [type] [description]
     */
    public function getRoomList($uid)
    {
        $map['status'] = 0;

        $mylist = $this->r_model
            ->where($map)
            ->whereIn('uid', $uid)
            ->with('user')
            ->find();

        $list = $this->r_model
            ->order('create_time desc')
            ->where($map)
            ->whereNotIn('uid', $uid)
            ->with('user')
            ->select();

        $result = [];
        array_push($result, $mylist);
        foreach ($list as $k => $v) {
            array_push($result, $v);
        }

        return [
            'code'  => 200,
            'datas' => json_encode($result)
        ];
    }

    /**
     * 创建联盟
     *
     * @param  [type] $uid  用户id
     * @param  [type] $name 联盟名称
     * @return [type]       [description]
     */
    public function createRoom($uid, $name)
    {
        if ($this->r_model->where(['uid' => $uid])->count() > 0) {
            return [
                'code' => 0,
                'msg'  => '您已创建过联盟'
            ];
        }

        $rid = $this->u_service->buildSixId('rooms');
        $save = [
            'rid' => $rid,
            'uid' => $uid,
            'name' => $name
        ];
        if ($this->r_model->save($save) > 0) {
            return [
                'code' => 200,
                'msg'  => '创建成功'
            ];
        } else {
            return [
                'code' => 0,
                'msg'  => '创建失败'
            ];
        }
    }
}
